#!/bin/bash

# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.
if [ -z $1 ]
then
  echo "You must provide a location to restore the configuration from" >&2
  echo >&2
  echo "Usage: $0 backup_directory" >&2
  exit 1
fi

local_site_name=site1
etcd_key=clearwater
. /etc/clearwater/config

backup_directory="$1"

top_key=${etcd_key}/${local_site_name}/configuration

# Check we can contact `etcd`
if ! nc -z ${management_local_ip:-$local_ip} 4000
then
  echo "Unable to contact etcd at ${management_local_ip:-$local_ip} on port 4000" >&2
  exit 2
fi

# Set null globbing so thatif there are no files in the directory,
# we don't attempt to upload a file named *.
shopt -s nullglob

FILES="${backup_directory}/*"

for f in $FILES
do
  key=$(basename $f)
  if [ $key != "apply_config" ]; then
    # Upload the file to etcd
    keypath=http://${management_local_ip:-$local_ip}:4000/v2/keys/${top_key}/$key
    tmp_file=/tmp/restore-config.$key
    curl -X PUT $keypath --data-urlencode value@${f} 2> ${tmp_file}.stderr.$$ | tee ${tmp_file}.stdout.$$ | egrep -q "\"action\":\"set\""
    rc=$?

    # Check the return code and log if appropriate.
    if [ $rc != 0 ] ; then
      echo "Failed to upload key $key to etcd with return code $rc" >&2
      cat ${tmp_file}.stderr.$$              >&2
      cat ${tmp_file}.stdout.$$              >&2
      exit 3
    fi

    rm -f ${tmp_file}.stderr.$$ ${tmp_file}.stdout.$$
  fi
done

